<template>
  <div id="demo">
    <div class="head-line">
      <img src="@/assets/icon/arrow-l.png" @click="cancelSubmit" alt />
      <h2>房屋详情</h2>
      <span></span>
    </div>
    <div class="demo-in">
      <div class="demo-inner">
        <div><span>户主：</span> {{ house.name }}</div>
        <div><span>门牌号：</span> {{ house.doorno }}</div>
        <div><span>工程状态：</span> {{ house.projectstatus }}</div>
        <div>
          <span>所在村组：</span> {{ house.village }} {{ house.address }}
        </div>
        <div>
          <span> 巡查人： </span>
          <input type="text" v-model="demoObj.checker" />
        </div>
        <div>
          <span>巡查时间： </span>
          <div
            class="time"
            v-html="demoObj.checkdate"
            @click="showPicker = true"
          ></div>
        </div>
        <div>
          <span>现场照片：</span>
          <van-uploader
            v-model="XCfileList"
            :after-read="XCRead"
            @delete="XCdelete"
            :max-count="1"
          />
        </div>
        <div class="textarea">
          <span>现场情况：</span>
          <textarea
            name=""
            id=""
            cols="30"
            rows="4"
            v-model="demoObj.localedescribe"
          ></textarea>
        </div>
        <div class="switch">
          <span>是否停工：</span>
          <van-switch v-model="demoObj.pause" :size="switchSize + 'px'" />
          {{ demoObj.pause ? "是" : "否" }}
        </div>
        <div class="switch">
          <span>是否需要整改：</span>
          <van-switch v-model="demoObj.isrectify" :size="switchSize + 'px'" />
          {{ demoObj.isrectify ? "是" : "否" }}
        </div>
        <div class="rectifyDemo" v-if="demoObj.isrectify">
          <div class="switch">
            <span>整改是否完成：</span>
            <van-switch
              v-model="demoObj.iscompelte"
              :size="switchSize + 'px'"
            />
            {{ demoObj.iscompelte ? "是" : "否" }}
          </div>
          <div>
            <span>整改证明：</span>
            <van-uploader
              v-model="ZMfileList"
              :after-read="ZMRead"
              @delete="ZMdelete"
              :max-count="1"
            />
          </div>
          <div>
            <span>整改完成现场照片：</span>
            <van-uploader
              v-model="WCfileList"
              :after-read="WCRead"
              @delete="WCdelete"
              :max-count="1"
            />
          </div>
          <div class="textarea">
            <span>整改措施：</span>
            <textarea
              name=""
              id=""
              cols="30"
              rows="4"
              v-model="demoObj.rectifystep"
            ></textarea>
          </div>
        </div>
      </div>
      <div class="btns">
        <!-- <button @click="submit">确定</button> -->
      <van-button type="info" size="large" color="#2e9be9" @click="submit">确定</van-button>
      </div>
    </div>
    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        v-model="pickTime"
        :item-height="optionHeight"
        type="date"
        show-toolbar
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
// 对于上传图片
// 如果是上传之前没有任何图片 提交保存的时候再上传（分开上传）
// 如果是新增上传图片的时候  那么需要对绑定的文件file进行判断
//      如果存在content和file则是新上传的文件，那么进行替换
//      上传的时候将   原数据   进行筛选完后  再将新增图片的数据添加进去
//      如果原数据进行了删除   那么通过
import local from "@/util/localstorage.js";
import api from "@/api/api.js";
import axios from "axios";

export default {
  name: "demo",
  data() {
    return {
      house: {},
      showPicker: false,
      demoObj: {
        pause: false,
        isrectify: false,
        iscompelte: false,
        checkdate: "",
      },
      switchSize: 50,
      optionHeight: 60,
      minDate: new Date("1990-01-01"),
      maxDate: new Date("2030-01-01"),
      // 选择器内的时间   如果直接绑定obj内的时间则造成滑动的时候就直接改变
      pickTime: new Date(),
      XCfileList: [],
      XClist: [],
      ZMfileList: [],
      ZMlist: [],
      WCfileList: [],
      WClist: [],
      imgHead:
        "http://house.ksljz.cn:8081/house/platform/system/sysFile/getFileById.do?fileId=",
    };
  },

  methods: {
    showDemo() {
      // 因为picktime在在滑动的时候已经被更改了   那么直接每次创建这个时间就行
      this.demoObj.checkdate = this.formatDate(new Date());
      this.demoObj.checker = local.getLoaclStorage("userInfo").fullname;
      //   var obj = local.getLoaclStorage("rectifyOrder");
      if (local.getLoaclStorage("rectifyOrder")) {
        var obj = local.getLoaclStorage("rectifyOrder");
      }
      // console.log(obj);
      if (obj) {
        Object.assign(this.demoObj, obj);
        this.demoObj.pause = this.demoObj.pause == "是" ? true : false;
        this.demoObj.isrectify = this.demoObj.isrectify == "是" ? true : false;
        this.demoObj.iscompelte =
          this.demoObj.iscompelte == "是" ? true : false;
        this.demoObj.checkdate = this.formatDate(this.demoObj.checkdate);
        this.pickTime = new Date(obj.checkdate); // 把时间选择器也绑定上时间
        if (obj.picture) {
          // console.log(this.imgHead + JSON.parse(obj.picture).attachs[0].fileId)
          let item1 = {
            url: this.imgHead + JSON.parse(obj.picture).attachs[0].fileId,
            isImage: true,
          };
          this.XCfileList[0] = item1;
        }
        if (obj.zgzmfile) {
          let item2 = {
            url: this.imgHead + JSON.parse(obj.zgzmfile).attachs[0].fileId,
            isImage: true,
          };
          this.ZMfileList[0] = item2;
        }
        if (obj.zgwcxczpfile) {
          let item3 = {
            url: this.imgHead + JSON.parse(obj.zgwcxczpfile).attachs[0].fileId,
            isImage: true,
          };
          this.WCfileList[0] = item3;
        }
      }
    },
    // 格式化时间戳     自定义返回  年月日时分秒
    formatDate(date) {
      var now = new Date(date);
      var year = now.getFullYear();
      // var year = now.getYear();     //  为啥是120
      // console.log(year);
      var month = now.getMonth() + 1;
      // if (month < 10) {
      //   month = "0" + month;
      // }
      month = (month + "").padStart(2, "0");
      var date = now.getDate();
      // if (date <script 10) {
      //   date = "0" + date;
      // }
      date = (date + "").padStart(2, "0");
      var hour = now.getHours();
      var minute = now.getMinutes();
      var second = now.getSeconds();
      return year + "-" + month + "-" + date;
    },
    // 时间选择器的取消
    onCancel() {
      this.pickTime = new Date(this.demoObj.checkdate);
      this.showPicker = false;
      // this.demoObj.isrectify = false;
    },
    // 时间选择器的确定
    onConfirm(value) {
      // console.log('点击到确定按钮了', value);
      this.pickTime = value;
      this.demoObj.checkdate = this.formatDate(value);
      this.showPicker = false;
    },
    async XCRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
  
      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.picture = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.picture = JSON.stringify(this.demoObj.picture);
        });
    },
    XCdelete(detail){
      console.log('现场删除..', detail)
      this.demoObj.picture = null
    },
    async ZMRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file.content);

      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      console.log(afterCompressBase64);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgzmfile = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.zgzmfile = JSON.stringify(this.demoObj.zgzmfile);
        });
    },
    ZMdelete(file){
      console.log('现场删除..', file)
      this.demoObj.zgzmfile = null
    },
    async WCRead(file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file.content);

      let afterCompressBase64 = await this.compressImg(file.content, 0.1);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgwcxczpfile = {
            attachs: [
              { fileId: response.data.fileId, fileSrc: afterCompressBase64 },
            ],
          };
          this.demoObj.zgwcxczpfile = JSON.stringify(this.demoObj.zgwcxczpfile);
        });
    },
    WCdelete(file){
      console.log('现场删除..', file)
      this.demoObj.zgwcxczpfile = null
    },
    cancelSubmit() {
      this.demoObj = this.$options.data().demoObj;
      this.XCfileList = [];
      this.ZMfileList = [];
      this.WCfileList = [];
      this.$router.go(-1);
    },
    submit() {
      // 校验表单内必填事项是有空值
      var arr = ["picture", "localedescribe"];
      var re = arr.every((item) => Boolean(this.demoObj[item]));
      // console.log(re)
      if (!re) {
        this.$toast.fail({ message: "数据未填写完整", forbidClick: true });
        return;
      }

      this.$toast.loading({ message: "加载中...", forbidClick: true });
      var obj = {
        id: this.demoObj.id,
        houseid: this.house.id,
        name: this.house.name,
        doorno: this.house.doorno,
        address: this.house.address,
        village: this.house.village,
        town: this.house.town,
        xy: this.house.xy,
        projectstatus: this.house.projectstatus,
        checker: this.demoObj.checker,
        checkdate: this.demoObj.checkdate,
        localedescribe: this.demoObj.localedescribe,
        picture: this.demoObj.picture, // 现场照片
        pause: this.demoObj.pause ? "是" : "否",
        isrectify: this.demoObj.isrectify ? "是" : "否",
        rectifystep: this.demoObj.rectifystep,
        iscompelte: this.demoObj.iscompelte ? "是" : "否",
        attach: "",
        remark: "",
        zgzmfile: this.demoObj.zgzmfile, // 整改证明图片
        zgwcxczpfile: this.demoObj.zgwcxczpfile, // 整改完成照片
        createBy: this.demoObj.checker,
        // createtime: new Date(),    // 防止创建时间一直被更改
        updatetime: null,
        updateBy: null,
        runId: null,
      };
      // 如果有id则说明是编辑  那么保存新增更新时间和更新人即可
      if (this.demoObj.id) {
        // obj.createBy = this.demoObj.createBy;
        obj.createtime = this.formatDate(this.demoObj.createtime);
        obj.updatetime = this.formatDate(new Date());
        obj.updateBy = this.demoObj.checker;
      } else {
        obj.createtime = this.formatDate(new Date());
      }
      var jsonData = JSON.stringify(obj);
      api
        .saveInspect(obj)
        .then((res) => {
          console.log(res);
          // this.showLoading = false;
          this.$toast.clear();
          if (res.data.success) {
            this.$toast.success("成功");
          } else {
            this.$toast.fail("失败");
          }
          // 不论成功与否  都得清除表单  重新拉出一下房屋巡查记录
          this.cancelSubmit();
        })
        .catch((error) => {
          // console.log(error)
          this.$toast.clear();
          this.$toast.fail("连接超时");
        });
    },

    compressImg(base64String, quality) {
      // 获取图片类型  image/png  image/jpg 之类的
      var getMimeType = function (urlData) {
        var arr = urlData.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        return mime;
      };
      var newImage = new Image();
      var originWidth, originHeight;

      var promise = new Promise((resolve) => (newImage.onload = resolve));
      newImage.src = base64String;
      return promise.then(() => {
        originWidth = newImage.width;
        originHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        // 最大尺寸限制
        var maxWidth = 80,
          maxHeight = 80;
        // 目标尺寸
        var targetWidth = originWidth,
          targetHeight = originHeight;
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }
        }

        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // console.log(newImage)
        ctx.clearRect(0, 0, targetWidth, targetHeight);
        ctx.drawImage(newImage, 0, 0, targetWidth, targetHeight);
        // document.body.appendChild(canvas)
        var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        return base64;
      });
    },
  },
  created() {
    this.house = local.getLoaclStorage("houseInfo");

    // 控制背景色
    var bg = document.querySelector("body");
    bg.style.backgroundColor = "#fff";

    this.showDemo();
  },
};
</script>

<style lang='scss' scoped>
#demo {
  width: 100%;
  height: 100%;
  .head-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 42px;
    padding: 0 23px;
    color: white;
    font-family: PingFangSC-Regular, sans-serif;
    background-color: #2e9be9;
    box-sizing: border-box;
    h2 {
      padding: 0;
      font-size: 20px;
      font-family: Adobe Heiti Std;
      font-weight: normal;
      color: #ffffff;
    }
    img {
      width: 20px;
      height: 20px;
    }
    span {
      display: inline-block;
      height: 30px;
      width: 40px;
      line-height: 30px;
    }
  }
  .demo-in {
    margin: 0 auto;
    padding: 10px;
    width: 100%;
    border-radius: 5px;
    box-sizing: border-box;
    background-color: #fff;
    overflow: hidden;
    .demo-inner {
      width: calc(100%);
      height: calc(100% - 40px);
      overflow-y: auto;
      > div {
        width: 100%;
        text-align: left;
        line-height: 25px;
        margin: 0 0 5px 0;
        span {
          display: inline-block;
          vertical-align: top;
          line-height: 25px;
          width: 100px;
        }
        input {
          width: 132px;
          height: 15px;
          line-height: 14px;
          border: 1px solid rgb(170, 170, 170);
        }
        > .time {
          display: inline-block;
          vertical-align: middle;
          line-height: 15px;
          width: 132px;
          height: 15px;
          border: 1px solid rgb(170, 170, 170);
        }
      }
      .textarea {
        margin-top: 10px;
        span {
          vertical-align: top;
        }
        textarea {
          width: calc(100% - 120px);
          border: 1px solid rgb(170, 170, 170);
        }
      }
      .switch {
        display: flex;
        align-items: center;
        line-height: 30px;
      }
      .rectifyDemo {
        .textarea {
          margin-top: 10px;
          span {
            vertical-align: top;
          }
          textarea {
            border: 1px solid rgb(170, 170, 170);
          }
        }
      }
    }
    .btns {
      width: 100%;
      height: 42px;
      margin-top: 10px;
      text-align: center;
      /deep/ .van-button {
        height: 42px;
      }
    }
  }
}
</style>
